/**
 * v-auth
 * @description 需要维护btnCodeMap，拿到权限code后和permissions中的functionCode比对
 */
import type { Directive, DirectiveBinding } from 'vue'
import { useUserStore } from '@/stores/user'
import { btnCodeMap } from '@/config/permissionMap'

const auth: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding
    const userStore = useUserStore()
    const permissions = userStore.permissions
    if (Array.isArray(value) && value.length) {
      const hasPermission = value.every((item) => {
        const code = (btnCodeMap as any)[item]
        return permissions.some(per => per.functionCode === code)
      })
      if (!hasPermission)
        el.remove()
    }
    else {
      const code = (btnCodeMap as any)[value]
      !permissions.some(per => per.functionCode === code) && el.remove()
    }
  },
}

export default auth
